﻿using System;
using System.Timers;
namespace OCDP.Client.Services.Clock
{
    // Todo : do not forget to register the service
    // container.RegisterType<IClockService,ClockService>();
    public class ClockService : IClockService, IDisposable
    {
        public event Action<DateTime> RaisedNewDateTime; 

        #region Fields
        private Timer timer;
        #endregion

        #region Constructor
        public ClockService()
        {
            int periode = 1000;
            timer = new Timer(periode);
            timer.Enabled = true;
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        }
        #endregion

        #region Methods

        public void Start()
        {
            if (!IsStarted) 
            {
                timer.Start();
                IsStarted = true;
            }                
        }

        public void Stop()
        {
            if (IsStarted)
            {
                timer.Stop();
                IsStarted = false;
            }     
        }

        public bool IsStarted { get; private set; }

        public void Dispose()
        {
            timer.Dispose();
        }
        #endregion

        #region helpers
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            var handler = RaisedNewDateTime;
            if (handler != null)
                handler(DateTime.Now);
        }
        #endregion
    }
}
